{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import tensorflow as tf\n",
    "from tensorflow.keras import layers,models,losses,metrics\n",
    "\n",
    "#函数形式的自定义评估指标\n",
    "@tf.function\n",
    "def ks(y_true,y_pred):\n",
    "    y_true = tf.reshape(y_true,(-1,))\n",
    "    y_pred = tf.reshape(y_pred,(-1,))\n",
    "    length = tf.shape(y_true)[0]\n",
    "    t = tf.math.top_k(y_pred,k = length,sorted=False)\n",
    "    y_pred_sorted = tf.gather(y_pred,t.indices)\n",
    "    y_true_sorted = tf.gather(y_true,t.indices)\n",
    "    cum_positive_ratio = tf.truediv(\n",
    "        tf.cumsum(y_pred_sorted),\n",
    "        tf.cast(tf.reduce_sum(y_true_sorted),tf.float32)\n",
    "    )\n",
    "    cum_negative_ratio = tf.truediv(\n",
    "        tf.cumsum(1 - y_pred_sorted),\n",
    "        tf.cast(tf.reduce_sum(1 - y_true_sorted),tf.float32)\n",
    "    )\n",
    "    ks_value = tf.reduce_max(tf.abs(cum_positive_ratio - cum_negative_ratio))\n",
    "    return ks_value\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.320833206\r\n"
     ]
    }
   ],
   "source": [
    "y_true = tf.constant([[1],[1],[1],[0],[1],[1],[1],[0],[0],[0],[1],[0],[1],[0]])\n",
    "y_pred = tf.constant([[0.6],[0.1],[0.4],[0.5],[0.7],[0.7],[0.7],\n",
    "                      [0.4],[0.4],[0.5],[0.8],[0.3],[0.5],[0.3]])\n",
    "tf.print(ks(y_true,y_pred))\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}